package cn.com.ly.dao.impl;

import cn.com.ly.dao.UserDAO;
import cn.com.ly.model.User;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Component;

@Component("userDAO")
public class UserDAOImpl implements UserDAO {

    private SimpleJdbcTemplate simpleJdbcTemplate;
    private JdbcTemplate jdbcTemplate;

    public SimpleJdbcTemplate getSimpleJdbcTemplate() {
        return simpleJdbcTemplate;
    }

    @Resource
    public void setSimpleJdbcTemplate(SimpleJdbcTemplate simpleJdbcTemplate) {
        this.simpleJdbcTemplate = simpleJdbcTemplate;
    }

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    @Resource
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void save(String name) {
        jdbcTemplate.update("INSERT INTO test.user (id,username,PASSWORD) VALUES (NULL,?,?)", new Object[]{name, name});
        System.out.println("user saved!");
        throw new RuntimeException("exception!");
    }

    @Override
    public List<Long> getUserIdList() {
        RowMapper mapper = new RowMapper() {
            @Override
            public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getLong(1);
            }
        };
//        jdbcTemplate.query("", null, new Object[]{});
        return jdbcTemplate.query("select * from test.user where 1=1", mapper);
    }

    @Override
    public List<Map<String, Object>> getUserList() {
        return jdbcTemplate.queryForList("select * from test.user where 1=1");
    }

    @Override
    public List<User> getUsers() {
        return (List<User>) this.jdbcTemplate.query("select * from test.user where 1=1", new UserMapper());
    }

    @Override
    public <T> List<T> list(Class<T> type, String sql, Object... args) {
        BeanPropertyRowMapper<T> rm = new BeanPropertyRowMapper<T>(type);
        rm.setPrimitivesDefaultedForNullValue(true);
        return this.jdbcTemplate.query(sql, rm, args);
    }

    private static final class UserMapper implements RowMapper {

        @Override
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user = new User();
            user.setId(rs.getInt("id"));
            user.setPassword(rs.getString("password"));
            user.setUsername(rs.getString("username"));
            return user;
        }
    }
}
